package com.wuliu.driver.controller;

import com.wuliu.driver.config.SendMessage;
import com.wuliu.driver.pojo.DriverUser;
import com.wuliu.driver.service.DriverUserService;
import com.wuliu.driver.util.Code;
import com.wuliu.driver.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/user")
public class DriverUserController {
    @Autowired
    private DriverUserService driverUserService;
    @Autowired
    private SendMessage sendMessage;
    @Autowired
    private StringRedisTemplate redisTemplate;

    //登录/注册
    @RequestMapping("/login")
    public Result login(@RequestBody DriverUser driverUser) {

        return driverUserService.login(driverUser);
    }

    //发送验证码
    @GetMapping("/sendCode/{phone}")
    public String forget(@PathVariable String phone) {
        double r = Math.random();
        int v = (int) (r * 899999 + 100000);
        //将验证码存到redis中，设置了过期时间为600秒
        redisTemplate.opsForValue().set(phone, v + "", 600, TimeUnit.SECONDS);
        sendMessage.sendcode(phone, String.valueOf(v));
        return "发送成功";
    }


    //忘记密码
    @PostMapping("/forget")
    public Result forget(@RequestBody DriverUser driverUser) {
        //从redis中获取验证码
        String s = redisTemplate.opsForValue().get(driverUser.getPhone());
        //判断验证码是否正确
        if (s != null) {
            if (s.equals(driverUser.getYzm())){
                //删除验证码
                redisTemplate.delete(driverUser.getPhone());
                return driverUserService.forget(driverUser);
            }
            return new Result(Code.GET_ERR, "验证码错误");
        }
        return new Result(Code.GET_ERR, "验证码已过期");
    }
    //验证码登录
    @PostMapping("/code")
    public Result code(@RequestBody DriverUser driverUser) {
        //从redis中获取验证码
        String s = redisTemplate.opsForValue().get(driverUser.getPhone());
        //判断验证码是否正确
        if (s != null) {
            if (s.equals(driverUser.getYzm())){
                //删除验证码
                redisTemplate.delete(driverUser.getPhone());
                return driverUserService.code(driverUser);
            }
            return new Result(Code.GET_ERR, "验证码错误");
        }
        return new Result(Code.GET_ERR, "验证码已过期");
    }

}
